/**
 * antd-mobile-v2  可拉动刷新组件
 * 使用方式与ListView基本一致，将PullToRefresh合并在一起，参数也合并
 * https://mobile.ant.design/components/list-view-cn/#components-list-view-demo-idxed
 */

import React, { FC, useEffect, useRef, useState } from 'react';
import { ListView, PullToRefresh } from 'antd-mobile-v2';
import _ from 'lodash';
import styles from './index.module.less';

interface AntdRefreshListProps {
  dataSource: Array<any>;
  height?: number;
  initialListSize?: number;
  [propsName: string]: any;
}


const AntdRefreshList: FC<AntdRefreshListProps> = (props) => {
  const {
    refreshing, // 是否处于正在下拉刷新的状态
    loadingMore, // 是否处于正在上拉加载更多的状态
    height, // 列表高度
    onRefresh, // 下拉刷新回调
    onEndReached, // 上拉加载更多回调
    renderRow, // 行数据
    initialListSize = 10, // 组件刚挂载的时候渲染多少行数据
    ListViewProps,
    PullToRefreshProps,
    paddingBottomstyle,
    showFooterText = true, // 是否显示底部文案
    enableRefresh = true, // 是否支持下拉刷新
    noMargin // 是否具有顶部margin
  }: Readonly<any> = props;

  const [dataSource, setDataSource] = useState(new ListView.DataSource({
    rowHasChanged: (row1, row2) => row1 !== row2
  }));

  const ListRef = useRef();

  useEffect(() => {
    setDataSource(dataSource.cloneWithRows(_.cloneDeep(props.dataSource)));
  }, [props.dataSource]);

  return (
    <ListView
      className={
        `${styles.listview} 
        ${paddingBottomstyle && styles.paddingBottomstyle} 
        ${!showFooterText && styles.noFooter} 
        ${noMargin && styles.noMargin}
        `
      }
      ref={ListRef}
      dataSource={dataSource}
      renderFooter={() => (
        !showFooterText ?
          <div className="flex-center" >
            {
              loadingMore ?
                <span><i className="iconfont iconjiazai mr-4" />加载中</span>
                : <span>加载完成</span>
            }
          </div>
          : null
      )}
      renderRow={renderRow}
      style={{
        height: height ? `${height}px` : '100%'
        // margin: '5px 0 0 0'
      }}
      pullToRefresh={
        enableRefresh ?
          <PullToRefresh
            direction="down"
            indicator={{
              deactivate: '下拉刷新',
              activate: '松开立即刷新',
              release: (
                <p className="flex-center"> <i className="iconfont iconjiazai mr-4" />正在刷新</p>
              ),
              finish: '刷新完成'
            }}
            refreshing={refreshing}
            onRefresh={onRefresh}
            {...PullToRefreshProps}
          />
          : null
      }
      onEndReached={onEndReached}
      initialListSize={initialListSize}
      {...ListViewProps}
    />
  );
};

export default AntdRefreshList;
